<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>尬聊--聊天室</title>
    <%- include  common %>
    <style>
        #chatroom {
            width: 400px;
            height: 460px;
            border: 1px solid darkgoldenrod;
            border-radius: 10px;
            overflow-y: auto;
        }
    </style>
</head>

<body>
    <%-  include('head',{title:'chat',username}) %>
    <h2 id="title" data-username="<%- username%>">尬聊--聊天室</h2>
    <div id="chatroom">

    </div>
    <input type="text" placeholder="请输入聊天内容" id="word">
    <button type="button" id="sendbtn">点击发送 </button>
    <%- include  foot %>
</body>
<script>
    // # 客户端 
    // 1. 连接服务器
    // 2. 发送消息到服务器
    // 3. 监听服务器转发过来的消息
    // 4. 监听服务器端的关闭 


    // 1. 连接服务器
    var ws = new WebSocket("ws://192.168.60.87:3900");
    //判断是否连接成功
    var username = $('#title').attr('data-username');
    ws.onopen = function () {
        // username = prompt('输入你的用户名..');
        console.log(username);
        // 2. 发送消息到服务器
        // ws.send(`${username}说：hello ~~ `);
        sendMsg('hello...','blue')
    }
    // 3. 监听服务器转发过来的消息
    ws.onmessage = function (data) {
        console.log(data);
        document.getElementById('chatroom').innerHTML += `${data.data}`
    }
    //时间
    function sendMsg(msg,color){
        var time = new Date();
        var hour = time.getHours();
        var min = time.getMinutes();
        ws.send(`<p style="color:${color}"> ${username} (${hour}:${min}) 说：${msg}</p>`)
    }


    sendbtn.onclick = function(){
        sendMsgByClick()
    }

    function sendMsgByClick(){
        sendMsg(word.value,'#666');
        word.value = ''
    }
    document.onkeydown = function(e){
        if(e.keyCode == 13){
            sendMsgByClick()
        }
    }

    // 4. 监听服务器端的关闭 异常
    // ws.onclose = function(){
    //     alert('服务器突然关闭了....')
    // }
    // ws.onerror = function(){
    //     alert('服务器端突然死机了....')
    // }
</script>

</html>